import * as THREE from '../../build/three.module.js'
import Stats from '../../jsm/libs/stats.module.js'
import { GLTFLoader } from '../../jsm/loaders/GLTFLoader.js'

const scene = new THREE.Scene();
scene.background = new THREE.Color(0xf0f0f0);

// 光线
let light = new THREE.DirectionalLight(0xefefff, 1.5);
light.position.set(1, 1, 1).normalize();
scene.add(light);

light = new THREE.DirectionalLight(0xefefff, 1.5);
light.position.set(-1, -1, -1).normalize();
scene.add(light);

// 环境光
// const al = new THREE.AmbientLight(0xefefff, .5);
// scene.add(al);

// 加载外部模型
const loader = new GLTFLoader();
let mixer;
loader.load('../../models/gltf/Horse.glb', gltf => {

  // 装载外部模型
  const mesh = gltf.scene.children[0];
  scene.add(mesh);
  mesh.scale.set(1.5, 1.5, 1.5);

  // 配置帧动画
  mixer = new THREE.AnimationMixer(mesh);
  mixer.clipAction(gltf.animations[0]).play();

});

const axisH = new THREE.AxisHelper(20);
scene.add(axisH);

const k = innerWidth / innerHeight,
      s = 75,
      camera = new THREE.PerspectiveCamera(s, k, 1, 10000);
camera.position.set(0, 300, 0);
camera.target = new THREE.Vector3(0, 150, 0);

const renderer = new THREE.WebGLRenderer();
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(innerWidth, innerHeight);
// 设置gamma值
renderer.gammaOutput = true; // gamma 亮度
renderer.gammaFactor = 2.2;
document.body.appendChild(renderer.domElement);

// 统计
const stats = new Stats();
document.body.appendChild(stats.dom);

// 监听页面尺寸变化
window.addEventListener('resize', () => {
  camera.aspect = innerWidth / innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(innerWidth, innerHeight);
});

let radius = 600;
let theta = 0;
const clock = new THREE.Clock();
const render = () => {
  theta += .1;

  camera.position.x = radius * Math.sin(THREE.Math.degToRad(theta));
  camera.position.z = radius * Math.cos(THREE.Math.degToRad(theta));

  camera.lookAt(camera.target);
  
  if (mixer) {
    mixer.update(clock.getDelta());
  }

  renderer.render(scene, camera);
}

(function animate() {
  requestAnimationFrame(animate);
  render();
  stats.update();
})();